package cn.yshujia.service.impl;

import cn.yshujia.domain.LoginUser;
import cn.yshujia.domain.entity.User;
import cn.yshujia.domain.vo.UserVO;
import cn.yshujia.encryption.AESEncrypt;
import cn.yshujia.enums.Info;
import cn.yshujia.mapper.UserMapper;
import cn.yshujia.repository.UserRepository;
import cn.yshujia.utils.RegexUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


/**
 * @author YShuJia
 * @create 2024/4/23
 * @description 用户登录
 */

@Service
public class UserLoginService implements UserDetailsService {
	
	@Resource
	UserMapper userMapper;
	
	@Resource
	UserRepository repository;
	
	public UserDetails loadUserByUsername(String username) {
		if (RegexUtils.isValidEmail(username)) {
			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(User::getEmail, AESEncrypt.encrypt(username));
			
			User user = userMapper.selectOne(queryWrapper);
			if (user != null) {
				UserVO vo = repository.getUser(user.getId());
				vo.setPassword(user.getPassword());
				return new LoginUser(vo);
			}
		}
		throw new UsernameNotFoundException(Info.NON_USER.getMessage());
	}
}
